<script setup>
import { ref, onMounted } from 'vue'
import useUserStore from '@/pinia/userInfo'
import { storeToRefs } from 'pinia'
import { Close } from '@element-plus/icons-vue'
import { addLately } from '@/api/user'
import { customAlphabet } from 'nanoid'
import { queryTermDispatches, appendTermDispatch, focusDispatch } from '@/api/user'
const emits = defineEmits(['addGame', 'update:modelValue'])
const { token, userInfo } = storeToRefs(useUserStore())
const isClient = window.electronAPI || window.__TAURI__
const dispatchList = ref()
const isShowList = ref(false)
const isMaxCount = ref(false)

// eslint-disable-next-line no-unused-vars
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: true
  },
  content_id: {
    type: [String, Number],
    default: ''
  },
  start_type: {
    type: String,
    default: ''
  },
  provider_id: {
    type: [String, Number],
    default: ''
  }
})

onMounted(() => {
  getDispatchList()
})

/**
 * @description 添加最近游戏
 */
const _addLately = async () => {
  try {
    await addLately({
      provider_id: props.provider_id,
      content_id: props.content_id
    })
  } catch (e) {
    console.log(e)
  }
}

/**
 * @description 追加调度
 */
const appendDispatch = async (dispatch_id, start_type) => {
  try {
    await appendTermDispatch({
      content_id: props.content_id,
      dispatch_id
    })
    showDispatch(dispatch_id, start_type)
  } catch (err) {
    console.log(err)
  }
}

/**
 * @description 选择调度列表
 */
const chooseDispatch = (item) => {
  if (!item.can_append && item.all_content_ids.indexOf(props.content_id) == -1) return
  const start_type = JSON.parse(item.content_extra || '{}').start_type
  if (item.all_content_ids.indexOf(props.content_id) > -1) {
    showDispatch(item.dispatch_id, start_type)
  } else {
    appendDispatch(item.dispatch_id, start_type)
  }
}

/**
 * @description 直接打开已有调度窗口
 */
const showDispatch = async (dispatch_id = '', start_type) => {
  closeDialog()
  if (start_type === 'client' || !start_type) {
    await focusDispatch({
      dispatch_id
    })
  } else {
    // 客户端打开浏览器窗口
    const url = `${window.location.origin}/#/playGame?gameId=${
      props.content_id
    }&token=${encodeURIComponent(token.value)}&dispatchId=${dispatch_id}`
    if (window.electronAPI) {
      window.electronAPI.sendMessage({
        type: 'openUrl',
        params: {
          url
        }
      })
    } else if (window.__TAURI__) {
      // await open(url)
    } else {
      window.open(``, 'playGame' + dispatch_id)
    }
  }
}

/**
 * @description 开启新调度
 */
const startDispatch = async () => {
  closeDialog()
  const nanoid = customAlphabet(
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
    32
  )
  const dispatchId = nanoid()
  if (props.start_type === 'client' || !props.start_type) {
    const hostIp = window.localStorage.getItem('host_id') || window.location.origin
    const params = JSON.stringify({
      token: token.value,
      uid: userInfo.value.uid,
      content_id: props.content_id,
      signal_url: userInfo.value.signal_url,
      dispatch_id: dispatchId,
      hostIp
    })
    if (isClient) {
      if (window.electronAPI.platform === 'win32') {
        const url = `pwtClient://${btoa(params)}`
        const deskUrl = `gameDesk://${btoa(params)}`
        await open(url)
        await open(deskUrl)
      } else {
        const params = {
          token: token.value,
          content_id: props.content_id,
          signal_url: userInfo.value.signal_url[0],
          uid: userInfo.value.uid,
          hostIp
        }
        window.electronAPI.sendMessage({
          type: 'openClient',
          params
        })
      }
    } else {
      const url = `pwtWeb://${btoa(params)}`
      window.location.href = url
    }
  } else {
    const url = `/#/playGame?gameId=${props.content_id}&token=${encodeURIComponent(
      token.value
    )}&dispatchId=${dispatchId}`
    if (window.electronAPI) {
      const host = window.location.origin
      window.electronAPI.sendMessage({
        type: 'openUrl',
        params: {
          url: host + url
        }
      })
    } else if (window.__TAURI__) {
      const host = window.localStorage.getItem('host_id') || window.location.origin
      await open(host + url)
    } else {
      window.open(
        `/#/playGame?gameId=${props.content_id}&dispatchId=${dispatchId}`,
        'playGame' + dispatchId
      )
    }
  }
  _addLately()
}

/**
 * @description 获取可用的调度列表
 */
const getDispatchList = async () => {
  const { list, remainDispatchCnt } = await queryTermDispatches({
    term_id: userInfo.value.uid,
    content_id: props.content_id
  })
  const allList = (list || []).filter((item) => item.client_id == token.value)
  dispatchList.value = allList
  // 如果列表为0，判断是否有剩余可调度数
  // 如果调度列表1，先判断当前调度是否可以追加(如果可以追加则直接追加)，然后判断是否有剩余调度数
  // 如果调度列表有多个，显示调度列表，然后判断是否有剩余调度数
  if (allList.length == 0) {
    if (remainDispatchCnt !== 0) {
      startDispatch()
    }
  } else if (allList.length == 1) {
    if (allList[0].can_append) {
      appendDispatch(allList[0].dispatch_id, allList[0].start_type)
      return
    } else {
      if (allList[0].all_content_ids.indexOf(props.content_id) == -1) {
        if (remainDispatchCnt !== 0) {
          startDispatch()
        }
      } else {
        isShowList.value = true
      }
    }
  } else {
    isShowList.value = true
  }
  if (remainDispatchCnt == 0) {
    isMaxCount.value = true
    isShowList.value = true
    return
  }
}

/**
 * @description 关闭调度列表
 */
const closeDialog = () => {
  emits('update:modelValue', false)
}
</script>
<template>
  <div class="dialog-tips flex justify-center items-center" v-if="isShowList">
    <div class="p-[25px] center mt-[-50px]">
      <div class="flex">
        <div class="flex-1 text-[#fff] font-bold">
          {{ isMaxCount ? '启动限制' : '已开启窗口列表' }}
        </div>
        <div class="right-[10px] top-[10px] cursor-pointer" @click="closeDialog">
          <el-icon size="20" color="#999"><Close /></el-icon>
        </div>
      </div>
      <div class="mt-[30px]">
        <div class="text-center pb-[20px]" v-if="isMaxCount">
          启动窗口数超过最大限制, 您可关闭其它程序或选择可用窗口进行开启
        </div>
        <div
          v-for="item in dispatchList"
          :key="item"
          @click="chooseDispatch(item)"
          :class="[
            'p-[20px] mt-[20px] bg-[#20222e]  rounded-md  flex justify-between',
            {
              'text-[#999]': !item.can_append,
              'hover:bg-[#222] cursor-pointer ':
                item.can_append || item.all_content_ids.indexOf(content_id) > -1
            }
          ]"
        >
          <div class="">
            <div class="font-bold">窗口程序：{{ item.all_content_names.join(', ') }}</div>
            <div v-if="item.all_content_ids.indexOf(content_id) > -1" class="mt-[10px] text-[12px]">
              当前程序已启动，点击可直接跳转
            </div>
          </div>
          <div>
            {{ !item.can_append && item.all_content_ids.indexOf(content_id) == -1 ? '不可用' : '' }}
          </div>
        </div>
      </div>
      <div v-if="!isMaxCount" class="pt-[20px] text-center text-[#999]">
        <span @click="startDispatch" class="cursor-pointer">您也可以开启新的窗口, 点击开启</span>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.dialog-tips {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  .center {
    width: 480px;
    min-height: 120px;
    border-radius: 8px;
    position: relative;
    background: #1b2b35;
    border: 1px #222 solid;
  }
}
</style>
